// 密码显示/隐藏切换
function togglePassword() {
    const passwordField = document.getElementById('password');
    const toggleBtn = document.querySelector('.password-toggle-btn');
    
    if (passwordField.type === 'password') {
        passwordField.type = 'text';
        toggleBtn.textContent = '🙈';
    } else {
        passwordField.type = 'password';
        toggleBtn.textContent = '👁️';
    }
}

// 显示提示信息
function showAlert(message, type) {
    const alertDiv = document.getElementById('alert');
    alertDiv.textContent = message;
    alertDiv.className = 'alert alert-' + type;
    alertDiv.style.display = 'block';
    
    if (type === 'success') {
        setTimeout(() => {
            alertDiv.style.display = 'none';
        }, 3000);
    }
}

// 表单提交处理
document.getElementById('loginForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value;
    const roomId = document.getElementById('roomId').value;
    const loginBtn = document.getElementById('loginBtn');
    
    // 基本验证
    if (!username) {
        showAlert('请输入用户名', 'error');
        return;
    }
    
    if (!password) {
        showAlert('请输入密码', 'error');
        return;
    }
    
    // 禁用按钮，防止重复提交
    loginBtn.disabled = true;
    loginBtn.textContent = '登录中...';
    
    try {
        // 构建表单数据
        const formData = new URLSearchParams();
        formData.append('username', username);
        formData.append('password', password);
        formData.append('roomId', roomId);
        
        // 发送登录请求
        const response = await fetch('/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: formData
        });
        
        const data = await response.json();
        
        console.log('登录响应:', data); // 调试日志
        
        if (data.code === 200) {
            showAlert('登录成功！正在跳转...', 'success');
            
            // 延迟跳转到聊天页面
            setTimeout(() => {
                window.location.href = 'chat.html';
            }, 1000);
        } else {
            // 登录失败
            showAlert(data.message || '登录失败，请检查用户名和密码', 'error');
            loginBtn.disabled = false;
            loginBtn.textContent = '登录';
        }
    } catch (error) {
        console.error('登录错误:', error);
        showAlert('网络错误，请检查连接后重试', 'error');
        loginBtn.disabled = false;
        loginBtn.textContent = '登录';
    }
});

// 页面加载时检查是否已登录
window.addEventListener('DOMContentLoaded', async function() {
    try {
        const response = await fetch('/auth/current');
        const data = await response.json();
        
        console.log('当前用户检查:', data); // 调试日志
        
        if (data.code === 200 && data.data && data.data.username) {
            // 已登录，直接跳转到聊天页面
            window.location.href = 'chat.html';
        }
    } catch (error) {
        // 未登录或检查失败，继续显示登录页面
        console.log('未登录或检查失败:', error);
    }
});

// 回车键提交
document.getElementById('password').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        document.getElementById('loginForm').dispatchEvent(new Event('submit'));
    }
});
